import json
import os
import re
import time

import docx
import tqdm

time_string = str(int(time.time()))
if os.path.isfile("html_out.json") is True:
    json_file_path_string = "html_out.json"  #
    with open(json_file_path_string, 'r', encoding='utf-8') as f:
        json_obj = json.load(f)
else:
    json_string = input("json file string >")
    json_obj = json.loads(json_string)

doc_template_filename_list = [
    "1_title_策划案.docx",
    "2_title_菏泽学院社团活动申请表.docx",
    "3_title_菏泽学院社团活动通知（校级）.docx",
    "4_title_宣传稿.docx",
    "5_title_总结稿.docx",
    "6_title_证书模板.docx",
    "7_title_证书申请表模板.docx",
]

index_dict = {}
for raw_obj in json_obj:
    for abs_i in raw_obj["absolute_index"]:
        abs_i = int(abs_i)
        if abs_i not in index_dict:
            index_dict[abs_i] = []
        index_dict[abs_i].append(int(raw_obj["dataIndex"]))


def validateTitle(title):
    """
    去除文件名中的非法字符
    :param title:
    :return:
    """
    rstr = r"[\/\\\:\*\?\"\<\>\|]"  # '/ \ : * ? " < > |'
    new_title = re.sub(rstr, "_", title)  # 替换为下划线
    return new_title


def replace_str(old_str: str, obj_str: str, paragraphs, tables):
    for p in paragraphs:
        if old_str in p.text:
            inline = p.runs
            for i in inline:
                if old_str in i.text:
                    text = i.text.replace(old_str, obj_str)
                    i.text = text
    # 更换表格中的文字
    for table in tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.text = run.text.replace(old_str, obj_str)


def main():
    title_data_index = 19
    title_string = validateTitle(json_obj[title_data_index - 1]["dataText"])
    root_path_string = os.path.join("out", title_string + "_" + time_string)
    if os.path.isdir(root_path_string) is not True:
        os.makedirs(root_path_string)
    with tqdm.tqdm(total=len(doc_template_filename_list)) as pbar:
        for docx_file in doc_template_filename_list:
            doc = docx.Document(r"template/%s" % docx_file)
            for key, value in index_dict.items():
                replace_str(".%d." % key, json_obj[value[0] - 1]["dataText"], doc.paragraphs, doc.tables)
                replace_str("010%d010" % key, json_obj[value[0] - 1]["dataText"], doc.paragraphs, doc.tables)
                replace_str("101%d101" % key, json_obj[value[0] - 1]["dataText"], doc.paragraphs, doc.tables)

            docx_file_name = docx_file.replace("title", title_string)
            doc.save(os.path.join(root_path_string, docx_file_name))
            pbar.update(1)
    with open(os.path.join(root_path_string, title_string+".json"), "w+", encoding='utf-8') as f:
        json.dump(json_obj, f, ensure_ascii=False, indent=4)


if __name__ == '__main__':
    main()
